let board = [];
let hasConflicted = [] //校验每个格子的移动次数
let score = 0;
let rows = 4,
    cols = 4
let startx,starty,endx,endy


$(document).ready(function () {
    prepareMobile()
    newGame()
})

function prepareMobile() {

    if (domWidth > 500) {
        gridWidth = 500;
        cellLength = 100;
        cellSpace = 20;
    }
    // 给整个棋盘格设置移动端属性
    
    $('#grid-container').css({
        width: gridWidth - 2 * cellSpace,
        height: gridWidth - 2 * cellSpace,
        padding: cellSpace,
        borderRadius: 0.02 * gridWidth
    })
    
}

function newGame() {
    // 初始化棋盘格
    init();

    // 在随机两个格子中生成数字
    genderOneNumber()
    genderOneNumber()
}

function init() {
    $('#best').text(best)
    $('#score').text('0')

    let grid = $('#grid-container');
    grid.html("")
    // 绘制棋盘
    for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {
            let div = $(document.createElement('div'))
            div.addClass('grid-cell')
            div.attr('id', 'grid-cell-' + i + '-' + j)
            div.css('top', getPosTop(i, j))
            div.css('left', getPosLeft(i, j))
            grid.append(div)
        }
    }

    $('#grid-container .grid-cell').css({
        width: cellLength,
        height: cellLength,
        borderRadius: 0.08 * cellLength
    })

    // 初始化棋盘的值
    for (let i = 0; i < rows; i++) {
        board[i] = []
        hasConflicted[i] = []
        for (let j = 0; j < cols; j++) {
            board[i][j] = 0
            hasConflicted[i][j] = false
        }
    }

    // 映射number值
    updataboardView()

    // 初始化分数
    score = 0
}


function updataboardView() {
    $('.number-cell').remove()
    let grid = $('#grid-container');
    for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {
            grid.append(`<div class="number-cell" id="number-cell-${i}-${j}"></div>`)
            let theNumberCell = $(`#number-cell-${i}-${j}`)

            if (board[i][j] === 0) {
                theNumberCell.css("width", "0px")
                theNumberCell.css("height", "0px")
                theNumberCell.css("top", getPosTop(i, j) + cellLength / 2)
                theNumberCell.css("left", getPosLeft(i, j) + cellLength / 2)
            } else {
                theNumberCell.css("width", cellLength)
                theNumberCell.css("height", cellLength)
                theNumberCell.css("top", getPosTop(i, j))
                theNumberCell.css("left", getPosLeft(i, j))
                theNumberCell.css("background-color", getNumberBackgroundColor(board[i][j]))
                theNumberCell.css("color", getNumberColor(board[i][j]))
                theNumberCell.text(board[i][j])
            }
            hasConflicted[i][j] = false
        }
        $('.number-cell').css('line-height', cellLength + 'px')
        $('.number-cell').css('font-size', cellLength * 0.6 + 'px')
    }
}

function genderOneNumber() {
    // 判断棋盘格是否还有空格
    if (!nospace(board)) {
        // 没空格
        return false
    }


    // 有空格
    // 随机位置
    let ranX = parseInt(Math.floor(Math.random() * cols))
    let ranY = parseInt(Math.floor(Math.random() * rows))

    let times = 0
    while (times < 50) {
        if (board[ranX][ranY] === 0) {
            break
        }

        ranX = parseInt(Math.floor(Math.random() * cols))
        ranY = parseInt(Math.floor(Math.random() * rows))
        times++
    }

    if (times == 50) {
        for (let i = 0; i < rows; i++) {
            for (let j = 0; j < cols; j++) {
                if (board[i][j] == 0) {
                    ranX = i
                    ranY = j
                }
            }
        }
    }

    // 随机数字
    let ranNumber = Math.random() > 0.5 ? 4 : 2

    // 在随机位置展示随机数字
    board[ranX][ranY] = ranNumber
    showNumberWithAnimation(ranX, ranY, ranNumber)
    return true
}

// 用户操作按键的上下左右按键操作游戏进行
$(document).keydown(function (e) {
    e.preventDefault()
    switch (e.keyCode) {
        case 37:
            if (moveLeft()) {
                setTimeout("genderOneNumber()", 210)
                setTimeout("isGameOver()", 300)
            }
            break;
        case 38:
            if (moveUp()) {
                setTimeout("genderOneNumber()", 210)
                setTimeout("isGameOver()", 300)
            }
            break;
        case 39:
            if (moveRight()) {
                setTimeout("genderOneNumber()", 210)
                setTimeout("isGameOver()", 300)
            }
            break;
        case 40:
            if (moveDown()) {
                setTimeout("genderOneNumber()", 210)
                setTimeout("isGameOver()", 300)
            }
            break;
        default:
            break;
    }
});

function isGameOver() {
    if (!nospace(board) && nomove(board)) {
        gameOver()
    }
}

function gameOver() {
    // alert('游戏结束，您的得分是' + score + '分')
    $('#cover-content').html(`<!-- 游戏结束页面 -->
    <div class="gameover-bg">
        <h3>${score}</h3>
    </div>
    <div class="gameover_btn_opt">
        <div id="gameover_again_btn"></div>
        <div id="gameover_paimin_btn"></div>
    </div>`)
    showModal()

    $('#gameover_again_btn').click(function(){
        newGame()
        closeModal()
    })

    // 本地保存最高分
    window.localStorage.setItem('2048bestScore', score)
}

function moveLeft() {
    if (!canMoveLeft(board)) {
        return false
    }
    // 向左移动的逻辑
    for (let i = 0; i < rows; i++) {
        for (let j = 1; j < cols; j++) {
            if (board[i][j] !== 0) {

                for (let k = 0; k < j; k++) {
                    if (board[i][k] === 0 && noRoadblockLevel(i, k, j, board)) {
                        //move

                        board[i][k] = board[i][j]
                        board[i][j] = 0
                        showMoveAnimation(i, j, i, k)
                        continue
                    } else if (board[i][k] === board[i][j] && noRoadblockLevel(i, k, j, board) && !hasConflicted[i][k]) {
                        // move
                        showMoveAnimation(i, j, i, k)
                        // add
                        board[i][k] += board[i][j]
                        board[i][j] = 0
                        score += board[i][k]
                        updataScoreAnimation(score)

                        hasConflicted[i][k] = true
                        continue
                    }

                }
            }
        }
    }
    setTimeout(function () {
        updataboardView()
    }, 200)
    return true
}

function moveUp() {
    if (!canMoveUp(board)) {
        return false
    }
    // 向上移动的逻辑
    for (let i = 1; i < rows; i++) {
        for (let j = 0; j < cols; j++) {
            if (board[i][j] !== 0) {
                for (let k = 0; k < i; k++) {
                    if (board[k][j] === 0 && noRoadblockVertical(j, k, i, board)) {
                        //move
                        showMoveAnimation(i, j, k, j)
                        board[k][j] = board[i][j]
                        board[i][j] = 0
                        continue
                    } else if (board[k][j] === board[i][j] && noRoadblockVertical(j, k, i, board) && !hasConflicted[k][j]) {
                        // move
                        showMoveAnimation(i, j, k, j)
                        // add
                        board[k][j] += board[i][j]
                        board[i][j] = 0
                        score += board[k][j]
                        updataScoreAnimation(score)
                        hasConflicted[k][j] = true
                        continue
                    }

                }
            }
        }
    }
    setTimeout(function () {
        updataboardView()
    }, 200)
    return true
}

function moveRight() {
    if (!canMoveRight(board)) {
        return false
    }
    // 向右移动的逻辑
    for (let i = 0; i < rows; i++) {
        for (let j = cols - 2; j >= 0; j--) {
            if (board[i][j] !== 0) {

                for (let k = cols - 1; k > j; k--) {
                    if (board[i][k] === 0 && noRoadblockLevel(i, j, k, board)) {
                        //move
                        showMoveAnimation(i, j, i, k)
                        board[i][k] = board[i][j]
                        board[i][j] = 0
                        continue
                    } else if (board[i][k] === board[i][j] && noRoadblockLevel(i, j, k, board) && !hasConflicted[i][k]) {
                        // move
                        showMoveAnimation(i, j, i, k)
                        // add
                        board[i][k] += board[i][j]
                        board[i][j] = 0
                        score += board[i][k]
                        updataScoreAnimation(score)
                        hasConflicted[i][k] = true
                        continue
                    }

                }
            }
        }
    }
    setTimeout(function () {
        updataboardView()
    }, 200)
    return true
}

function moveDown() {
    if (!canMoveDown(board)) {
        return false
    }
    // 向下移动的逻辑
    for (let i = rows - 2; i >= 0; i--) {
        for (let j = 0; j < cols; j++) {
            if (board[i][j] !== 0) {
                for (let k = rows - 1; k > i; k--) {
                    if (board[k][j] === 0 && noRoadblockVertical(j, i, k, board)) {
                        //move
                        showMoveAnimation(i, j, k, j)
                        board[k][j] = board[i][j]
                        board[i][j] = 0
                        continue
                    } else if (board[k][j] === board[i][j] && noRoadblockVertical(j, i, k, board) && !hasConflicted[k][j]) {
                        // move
                        showMoveAnimation(i, j, k, j)
                        // add
                        board[k][j] += board[i][j]
                        board[i][j] = 0
                        score += board[k][j]
                        updataScoreAnimation(score)
                        hasConflicted[k][j] = true
                        continue
                    }

                }
            }
        }
    }
    setTimeout(function () {
        updataboardView()
    }, 200)
    return true
}

document.getElementById('grid-container').addEventListener('touchstart',function(e){
    e.preventDefault()
    startx = e.touches[0].pageX
    starty = e.touches[0].pageY
})

document.getElementById('grid-container').addEventListener('touchend',function(e){
    e.preventDefault()
    endx = e.changedTouches[0].pageX
    endy = e.changedTouches[0].pageY
    
    let changex = endx-startx
    let changey = endy-starty

    if(Math.abs(changex)<0.1*domWidth&&Math.abs(changey)<0.1*domWidth){
        return
    }

    // Math.abs()为取绝对值
    if(Math.abs(changex)>Math.abs(changey)){
        // 想像x轴滑动
        if(changex>0){
            // 向右方向滑动
            if (moveRight()) {
                setTimeout("genderOneNumber()", 210)
                setTimeout("isGameOver()", 300)
            }
        }else{
            // 向左方向滑动
            if (moveLeft()) {
                setTimeout("genderOneNumber()", 210)
                setTimeout("isGameOver()", 300)
            }
        }
    }else{
        // 想像y轴滑动
        if(changey>0){
            // 向下滑动
            if (moveDown()) {
                setTimeout("genderOneNumber()", 210)
                setTimeout("isGameOver()", 300)
            }
        }else{
            // 向上滑动
            if (moveUp()) {
                setTimeout("genderOneNumber()", 210)
                setTimeout("isGameOver()", 300)
            }
        }
    }
})